package cn.jksoft.businessclient.ui.fragment;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.jksoft.businessclient.R;
import cn.jksoft.businessclient.api.ReceivingService;
import cn.jksoft.businessclient.base.BaseApplication;
import cn.jksoft.businessclient.base.BaseFragment;
import cn.jksoft.businessclient.bean.BaseEntity;
import cn.jksoft.businessclient.bean.WorkBenchEntity;
import cn.jksoft.businessclient.ui.activity.CreateOrderActivity;
import cn.jksoft.businessclient.ui.activity.LoginActivity;
import cn.jksoft.businessclient.ui.activity.OrderDetailActivity;
import cn.jksoft.businessclient.ui.activity.OrderSettlementActivity;
import cn.jksoft.businessclient.ui.adapter.WorkbenchAdapter;
import cn.jksoft.businessclient.ui.views.RecycleViewDivider;
import cn.jksoft.businessclient.utils.DialogHelp;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Author:  nick
 * Email:   nickdevp@gmail.com
 * Date:    16/04/07
 * Description:
 */
public class WorkbenchFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener{
    @Bind(R.id.swipe_container)
    SwipeRefreshLayout mSwipeLayout;
    @Bind(R.id.recyclerview_order_list)
    RecyclerView mRecyclerView;
    @Bind(R.id.ll_empty_source)
    LinearLayout mEmptySourceLayout;
    @Bind(R.id.btn_create_order)
    Button btnCreateOrder;

    private LinearLayoutManager linearLayoutManager;
    private int lastVisibleItem;
    private boolean isLoadMore;
    private WorkbenchAdapter adapter;
    private int pageNo = 1;
    private boolean isNoMore;

    private ProgressDialog progressDialog;

    private List<WorkBenchEntity.OrderMapBean.DataBean> dataBeanList;

    @Override
    public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_workbench, container,
                false);
        ButterKnife.bind(this, view);
        if(BaseApplication.getInstance().getLoginEntity() == null){
            getActivity().finish();
            readyGo(LoginActivity.class);
        }
        initView();
        return view;
    }

    private void initView(){
        linearLayoutManager = new LinearLayoutManager(getActivity());
        mSwipeLayout.setProgressViewOffset(false, 0, (int) TypedValue
                .applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24, getResources()
                        .getDisplayMetrics()));
        mRecyclerView.setLayoutManager(linearLayoutManager);
        mRecyclerView.addItemDecoration(new RecycleViewDivider(getActivity(), LinearLayoutManager.VERTICAL));
        dataBeanList = new ArrayList<WorkBenchEntity.OrderMapBean.DataBean>();
        adapter = new WorkbenchAdapter(getActivity(), dataBeanList);
        adapter.setButtonClickListenner(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                WorkBenchEntity.OrderMapBean.DataBean bean = dataBeanList.get((int)(v.getTag()));
                if(bean.getSERVICE_STATUS() == 0) {
                    completeOrder(bean.getOUTBOUND_ID()+"");
                }else{
                    Bundle bundle = new Bundle();
                    bundle.putString("outboundId", bean.getOUTBOUND_ID());
                    bundle.putString("carPlateNum", bean.getCAR_PLATE_NUM());
                    bundle.putString("messageId",bean.getMessId());
                    readyGoForResult(OrderSettlementActivity.class,0, bundle);
                }
            }
        });
        adapter.setItemClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                WorkBenchEntity.OrderMapBean.DataBean bean = dataBeanList.get((int)(v.getTag()));
                bean.setIsHasNewMess("N");
                Bundle bundle = new Bundle();
                if(bean.getSERVICE_STATUS() == 0) {
                    bundle.putBoolean("isShowAdd",true);
                }
                bundle.putString("outboundId", bean.getOUTBOUND_ID());
                bundle.putString("carPlateNum", bean.getCAR_PLATE_NUM());
                bundle.putString("messageId",bean.getMessId());
                readyGo(OrderDetailActivity.class, bundle);
                adapter.notifyDataSetChanged();
            }
        });
        mRecyclerView.setAdapter(adapter);
        mSwipeLayout.setOnRefreshListener(this);
        mSwipeLayout.setColorSchemeResources(R.color.colorPrimary, android.R.color.holo_green_light,
                android.R.color.holo_orange_light, R.color.colorPrimary);
        mSwipeLayout.setDistanceToTriggerSync(400);
        mSwipeLayout.setColorSchemeColors(R.color.white);
        mSwipeLayout.setRefreshing(true);
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState ==RecyclerView.SCROLL_STATE_IDLE && lastVisibleItem + 1 ==adapter.getItemCount()) {
                    if(!isLoadMore) {
                        if(!isNoMore){
                            getOrderData();
                        }
                    }
                    isLoadMore = true;
                }
            }
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView,dx, dy);
                lastVisibleItem =linearLayoutManager.findLastVisibleItemPosition();
            }
        });
        btnCreateOrder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                readyGo(CreateOrderActivity.class);
            }
        });
        getOrderData();
    }

    private void getOrderData(){
        mEmptySourceLayout.setVisibility(View.GONE);
        JSONObject json = null;
        try {
            json = new JSONObject();
            json.put("storeId", BaseApplication.getInstance().getLoginEntity().getPuxsoftLoginDTO().getStoreId()+"");
            json.put("operId",BaseApplication.getInstance().getLoginEntity().getPuxsoftLoginDTO().getAdminUserId());
            json.put("pageSize", "10");
            json.put("pageNo",pageNo+"");
        } catch (Exception e) {
            e.printStackTrace();
        }
        ReceivingService.createReceivingService().getOrderList(json.toString())
                .observeOn(Schedulers.io())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<WorkBenchEntity>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(WorkBenchEntity workBenchEntity) {
                        if("1".equals(workBenchEntity.getIs_successful())) {
                            if(workBenchEntity.getOrderMap().getData()!=null) {
                                if(pageNo == 1){
                                    dataBeanList.clear();
                                }
                                if(workBenchEntity.getOrderMap().getData().size()>=10){
                                    pageNo++;
                                }else{
                                    isNoMore = true;
                                }
                                dataBeanList.addAll(workBenchEntity.getOrderMap().getData());
                                adapter.notifyDataSetChanged();
                            }
                        }
                        if(dataBeanList == null || dataBeanList.size() == 0){
                            mEmptySourceLayout.setVisibility(View.VISIBLE);
                        }
                        isLoadMore = false;
                        mSwipeLayout.setRefreshing(false);
                    }
                });
    }

    private void completeOrder(String outboundId){
        progressDialog = DialogHelp.getWaitDialog(getActivity(),"正在执行...");
        progressDialog.show();
        JSONObject json = null;
        try {
            json = new JSONObject();
            json.put("storeId", BaseApplication.getInstance().getLoginEntity().getPuxsoftLoginDTO().getStoreId());
            json.put("operId",BaseApplication.getInstance().getLoginEntity().getPuxsoftLoginDTO().getAdminUserId());
            json.put("outboundId", outboundId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        ReceivingService.createReceivingService().completeOrder(json.toString())
                .observeOn(Schedulers.io())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseEntity>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        progressDialog.dismiss();
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(BaseEntity entity) {
                        if("1".equals(entity.getIs_successful())) {
                            mSwipeLayout.setRefreshing(true);
                            pageNo = 1;
                            getOrderData();
                        }else{
                            showToast(entity.getResult());
                        }
                        progressDialog.dismiss();

                    }
                });
    }

    @Override
    public void onRefresh() {
        pageNo = 1;
        getOrderData();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == getActivity().RESULT_OK){
            pageNo = 1;
            getOrderData();
        }
    }
}
